package com.soul.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.soul.model.db.User;
import com.soul.server.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author mdoya
 * @version 1.0
 * @description: 配置拦截器
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.打印请求路径信息
        String requestMethod = request.getMethod();
        log.info("请求了路径: {}:{}", requestMethod, request.getRequestURI());
        if (handler instanceof HandlerMethod) {
            // 找出调用的哪个controller中的方法
            HandlerMethod method = (HandlerMethod) handler;
            if (null != method) {
                log.info("执行了: " + method.getShortLogMessage());
            }
        }
        // 有权限
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token)){
            String redisUser = stringRedisTemplate.opsForValue().get("TOKEN_" + token);
            if (StringUtils.isNotEmpty(redisUser)){
                User user = JSON.parseObject(redisUser, User.class);
                UserHolder.setUser(user);
                stringRedisTemplate.expire("TOKEN_" + token,30, TimeUnit.MINUTES);
                return true;
            }

        }
        // 无权限
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return false;
    }
}
